package com.tsfyun.scm.service.impl.customer;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.text.StrSpliter;
import com.tsfyun.common.base.util.StringUtils;
import com.tsfyun.scm.entity.customer.CustomerPersonChange;
import com.tsfyun.common.base.extension.ServiceImpl;
import com.tsfyun.scm.entity.user.Person;
import com.tsfyun.scm.service.customer.ICustomerPersonChangeService;
import com.tsfyun.scm.vo.customer.CustomerPersonChangeVO;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *

 * @since 2020-03-12
 */
@Service
public class CustomerPersonChangeServiceImpl extends ServiceImpl<CustomerPersonChange> implements ICustomerPersonChangeService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSaleChange(Long customerId,Person oldPerson, Person nowPerson, String memo) {
        saveChange(customerId,oldPerson,nowPerson,0,memo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBusChange(Long customerId,Person oldPerson, Person nowPerson, String memo) {
        saveChange(customerId,oldPerson,nowPerson,1,memo);
    }

    public void saveChange(Long customerId,Person oldPerson, Person nowPerson,Integer type, String memo){
        CustomerPersonChange change = new CustomerPersonChange();
        if(Objects.nonNull(oldPerson)){
            change.setOldPersonId(oldPerson.getId());
            change.setOldPersonName(oldPerson.getName());
        }
        if(Objects.nonNull(nowPerson)){
            change.setNowPersonId(nowPerson.getId());
            change.setNowPersonName(nowPerson.getName());
        }
        change.setCustomerId(customerId);
        change.setMemo(memo);
        change.setPersonType(type);
        super.save(change);
    }

    @Override
    public List<CustomerPersonChangeVO> records(@NonNull Integer personType, @NonNull Long customerId) {
        CustomerPersonChange condition = new CustomerPersonChange();
        condition.setPersonType(personType);
        condition.setCustomerId(customerId);
        List<CustomerPersonChange> list = super.list(condition);
        if(CollectionUtil.isNotEmpty(list)) {
            list = list.stream().sorted(Comparator.comparing(CustomerPersonChange::getDateCreated).reversed()).collect(Collectors.toList());
        }
        List<CustomerPersonChangeVO> dataList = beanMapper.mapAsList(list,CustomerPersonChangeVO.class);
        dataList.stream().forEach(r->{
            List<String> users = StrSpliter.split(r.getCreateBy(),"/",true,true);
            r.setOperator(users.size() > 1 ? users.get(1) : null);
        });
        return dataList;
    }

}
